package com.yitiao.data_algorithms.leetcode.editor.cn;

import com.yitiao.data_algorithms.leetcode.editor.cn.base.TreeNode;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

class ClosestNodesQueriesInABinarySearchTree {
    // 2024-02-24 10:55:09
    public static void main(String[] args) {
        Solution solution = new ClosestNodesQueriesInABinarySearchTree().new Solution();
    }

    //leetcode submit region begin(Prohibit modification and deletion)

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     * int val;
     * TreeNode left;
     * TreeNode right;
     * TreeNode() {}
     * TreeNode(int val) { this.val = val; }
     * TreeNode(int val, TreeNode left, TreeNode right) {
     * this.val = val;
     * this.left = left;
     * this.right = right;
     * }
     * }
     */
    class Solution {
        public List<List<Integer>> closestNodes(TreeNode root, List<Integer> queries) {
            List<List<Integer>> ans = new ArrayList<>(queries.size());
            List<Integer> treeValueList = new ArrayList<>();
            dfs(root, treeValueList);
            for (Integer query : queries) {
                // 二分查找
                int left = 0, right = treeValueList.size() - 1;
                while (left <= right) {
                    int mid = left + ((right - left) >> 1);
                    Integer midValue = treeValueList.get(mid);
                    if (Objects.equals(midValue, query)) {
                        right = mid;
                        left = mid;
                        break;
                    } else if (midValue > query) {
                        right = mid - 1;
                    } else {
                        left = mid + 1;
                    }
                }
                List<Integer> list = new ArrayList<>();
                if (left >= treeValueList.size()) {
                    list.add(treeValueList.get(treeValueList.size() - 1));
                    list.add(-1);
                } else if (right < 0) {
                    list.add(-1);
                    list.add(treeValueList.get(0));
                } else {
                    list.add(treeValueList.get(right));
                    list.add(treeValueList.get(left));
                }
                ans.add(list);
            }
            return ans;
        }

        private void dfs(TreeNode root, List<Integer> treeValueList) {
            if (root == null) return;
            dfs(root.left, treeValueList);
            treeValueList.add(root.val);
            dfs(root.right, treeValueList);
        }
    }
//leetcode submit region end(Prohibit modification and deletion)

}